#include "Helpers.h"

void StringFromPDEText(CString& str, PDEText text)
{
	ASInt32 length = PDETextGetNumChars(text);

	ASUns8* buffer = (ASUns8*)str.GetBufferSetLength(length);

	buffer[0] = '\0';

	int bufferOffset = 0;

	ASUns8* tmp = new ASUns8[length*2];

	for(int run = 0; run < PDETextGetNumRuns(text); ++run)
	{
		PDETextItem textItem = PDETextGetItem(text, run);

		//bufferOffset += PDETextItemCopyText(textItem, buffer + bufferOffset, length - bufferOffset);

		int len = PDETextItemCopyText(textItem, tmp, length*2);
		
		PDEFont pdeFont = PDETextItemGetFont (textItem);
		CosObj cosObj;
		PDEFontGetCosObj (pdeFont, &cosObj);
		PDFont pdFont = PDFontFromCosObj (cosObj);

		bufferOffset += PDFontXlateToUCS (pdFont, tmp, len, buffer + bufferOffset, length*2 - bufferOffset);
	}
	
	// strange, but it seems like PDFontXlateToUCS UTF-2byte-codes in reverse order
	ASUns8 t;
	for(int i = 0; i < length; ++i)
	{
		t = buffer[i*2];
		buffer[i*2] = buffer[i*2 + 1];
		buffer[i*2 + 1] = t;
	}

	delete[] tmp;

	str.ReleaseBuffer(length);
}


ASAtom ASAtomFromString2(CString& str)
{
	ASText asText = ASTextFromUnicode((ASUTF16Val*)str.GetBuffer(), kUTF16HostEndian);
	ASTArraySize len;
	char *buffer = ASTextGetPDTextCopy (asText,&len);
	ASTextDestroy (asText);
	
	ASAtom atom = ASAtomFromString(buffer);
	
	ASfree(buffer);

	return atom;

}


void CreateContainer(PDEContainer& pdeContainer, PDEContent& pdeContent, ASAtom tag)
{
	 pdeContainer = PDEContainerCreate(tag, NULL, false);
	 pdeContent = PDEContentCreate();
	 PDEContainerSetContent (pdeContainer, pdeContent);
 }